package cuit.campus.taskRunning.admin.config;


import cuit.campus.taskRunning.admin.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private JwtAuthenticationTokenFilter JwtAuthenticationTokenFilter;
    /**
     * 配置密码
     * @return
     */
    @Bean
    public BCryptPasswordEncoder encryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置Spring Security的过滤链。
     *
     * @param http 用于构建安全配置的HttpSecurity对象。
     * @return 返回配置好的SecurityFilterChain对象。
     * @throws Exception 如果配置过程中发生错误，则抛出异常。
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                //Spring Security 默认开启 CSRF 保护，主要用于防范浏览器端的跨站请求伪造。但如果你的接口是给 移动端、Postman、
                // 前端 Ajax 等非浏览器客户端调用，且未传递 CSRF Token，Spring Security 会直接拦截请求
                .csrf(csrf -> csrf.disable())
                //设置无状态 Spring Security 会默认尝试创建 Session，而无状态请求中没有 Session 信息
                . sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //配置放行路径
                .authorizeHttpRequests(auth -> auth
                        .antMatchers("/user/login/**", "/user/register/**")
                        .permitAll()
                        // 放行OPTIONS预检请求（关键：解决跨域时OPTIONS请求被拦截的问题）
                        .antMatchers("/**")
                        .permitAll()
                        .anyRequest().authenticated()
                )
                //将令牌校验过滤器放在
                .addFilterBefore(JwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
    // 定义AuthenticationManager Bean
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

}
